<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <link href="./styles/reset.css" rel="stylesheet" type="text/css">
    <link href="./styles/index.css" rel="stylesheet" type="text/css">

    <script src="./js/jquery.min.js" type="text/javascript"></script>
    <script src="./js/vue.min.js" type="text/javascript"></script>
    <!-- <script src="./js/eruda.min.js" type="text/javascript"></script>
    <script>eruda.init();</script> -->
</head>

<body>
    <div id="app" v-cloak>
        <div v-show="loading" class="basicLoading">
            <img src="./img/loading.gif">
        </div>
        <div v-show="showMsg" class="basicMsg">
            <div style="padding:6vw;font-size:3.5vw;">
                {{showMsg}}
            </div>
        </div>
        <div v-show="!loading" class="wrapper">
            <img src="./img/logo.png" class="logo" alt="logo" />
            <img @click="exit" src="./img/back.png" class="back" alt="back" />
            <div class="main" v-if="currentQuestion&&!infoFlag">
                <div class="title">{{ currentQuestion.question }}</div>
                <div class="timer-wrapper">
                    <svg viewbox="0 0 440 440">
                        <circle cx="220" cy="220" r="170" stroke-width="30" stroke="rgb(38,116,96)"
                            fill="rgb(31,113,111)"></circle>
                        <circle cx="220" cy="220" r="170" stroke-width="30" stroke="rgb(251, 187, 51)" fill="none"
                            transform="matrix(0,-1,1,0,0,440)" :stroke-dasharray="circlePercent"></circle>
                    </svg>
                    <span>{{ Math.ceil(timeCount) }}</span>
                </div>
                <div v-for="(item, cIdx) in currentQuestion.choices" class="choice-item"
                    :class="{'choice-color':choicesList[currentIndex] === item.prefix}"
                    @click="handleChioce(cIdx, item)">
                    {{ item.prefix }}: {{item.content}}
                </div>
                <div class="tool">
                    <span>第
                        <span style="color: rgb(225,156,125);">{{currentIndex + 1}} </span>题
                        共 {{questionList.length}} 题 </span>
                </div>
            </div>
            <div class="main" v-if="currentIndex >= questionList.length && !infoFlag">
                <div class="title">答题结束</div>
                <div class="score">
                    <div style="width:50%;">
                        <div class="round">
                            <div>
                                <div>{{ Math.ceil(timeCount) }}</div>
                            </div>
                        </div>
                    </div>

                    <div class="tip-wrapper">
                        <div class="main_tip">恭喜您！完成答题</div>
                        <div class="tip">答对 {{ answerNum.right }}</div>
                        <div class="tip">答错 {{ answerNum.wrong }}</div>
                        <div class="tip">成绩 {{ answerNum.right * 10 }}</div>
                    </div>
                </div>
                <div class="btn-group">
                    <div @click="restart">重新答题</div>
                    <div @click="goInfo">答题详情</div>
                    <div @click="exit">退出答题</div>
                </div>
            </div>
            <div class="main main2" v-if="infoFlag">
                <div class="title2">答题详情</div>

                <div style="display: flex;justify-content: space-around;">
                    <div class="choice-wrapper">
                        <div class="resultList" v-for="(i, index) in questionList" :key="i.id">
                            <div class="question">{{index + 1}}. {{i.question}}</div>
                            <div v-for="(item, cIdx) in i.choices" :key="i.cIdx" class="chioce-item2">
                                {{item.prefix }}: {{item.content}}
                                <img src="./img/yes.png" v-if="item.isAnswer" class="yes" alt="yes">
                            </div>

                            <div class="user_answer"
                                :class="{'right':choicesList[index]==i.choices.find(item=>item.isAnswer).prefix}">
                                你的答案是 {{ choicesList[index] }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>
</body>
<script>

    // 测试地址：index.html?baseUrl=http://101.133.148.108:8000&tenant_id=1&label_name=类型一&count=5&timeCount=20&logTitle=禁毒答题&logMode=index&manual_start=1

    const baseUrl = kindId("baseUrl"),//服务端地址
        tenant_id = kindId("tenant_id"),//租户id
        label_name = kindId("label_name"),//题目标签名
        count = kindId("count"),//题目数量
        timeCount = kindId("timeCount"),//答题倒计时
        logTitle = kindId("logTitle"),//统计回传的游戏标题
        logMode = kindId("logMode") || "index",//统计回传的题号字段
        manual_start = kindId("manual_start") || false;//是否禁止自动开始

    function kindId(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
            return decodeURI(r[2]);
        } else {
            return false;
        };
    }

    var app = new Vue({
        el: '#app',
        data: {
            loading: true,
            showMsg: null,
            questionList: [],
            currentIndex: 0,
            choicesList: [],
            timeCount: timeCount,
            btnLoading: true,
            infoFlag: false,
            answerNum: {
                right: 0,
                wrong: 0
            },
            circlePercent: '0 1069'
        },
        computed: {
            currentQuestion() {
                return this.questionList[this.currentIndex];
            }
        },
        mounted() {
            if (!manual_start) {
                this.restart();
            }
        },
        methods: {
            restart() {
                this.reset();
                this.getQuestionList();
                this.handleTimerCount(this.exit);
            },
            goInfo() {
                clearTimeout(this.timer);
                this.infoFlag = true;
            },
            reset() {
                clearTimeout(this.timer);
                this.answerNum = {
                    right: 0,
                    wrong: 0
                };
                this.btnLoading = true;
                this.infoFlag = false;
                this.questionList = [];
                this.currentIndex = 0;
                this.choicesList = [];
                this.timeCount = timeCount;
                this.circlePercent = '0 1069';
            },
            handleTimerCount(callback) {
                clearTimeout(this.timer);
                if (Math.ceil(this.timeCount > 0)) {
                    this.timer = setTimeout(() => {
                        this.timeCount -= 0.1;
                        var percent = (timeCount - this.timeCount) / timeCount;
                        var perimeter = Math.PI * 2 * 170;
                        this.circlePercent = `${percent * perimeter} 1069`;
                        this.handleTimerCount(callback);
                    }, 100);
                } else {
                    callback && callback();
                }
            },
            handleChioce(idx, row) {
                if (!this.btnLoading) return;
                this.choicesList.push(row.prefix);
                if (row.isAnswer) {
                    this.answerNum.right++;
                } else {
                    this.answerNum.wrong++;
                }
                this.btnLoading = false;
                setTimeout(() => {
                    this.currentIndex++;
                    this.circlePercent = '0 1069';
                    if (this.currentIndex >= this.questionList.length) {
                        this.timeCount = 50;
                        this.handleTimerCount(this.exit);
                        this.submitResults();
                        return;
                    }
                    this.timeCount = timeCount;
                    this.handleTimerCount(this.exit);
                    this.btnLoading = true;
                }, 300);
            },
            getQuestionList() {
                this.loading = true;
                $.get(`${baseUrl}/api/frontend_question/`, {
                    tenant_id,
                    label_name,
                    count
                }, (res) => {
                    this.loading = false;
                    this.questionList = res.data.map((item, index) => {
                        return {
                            id: item.id,
                            index: index,//序号
                            question: item.question,//问题
                            reserve: item.reserve,//解析
                            // hasSelected: false,
                            choices: item.choices.map((answer, answerIndex) => {//答案列表
                                return {
                                    prefix: String.fromCharCode(64 + parseInt(answerIndex + 1)),//前缀
                                    content: answer.content,//答案内容
                                    isAnswer: answer.checked,//正确答案
                                    // hasSelected: false
                                };
                            })
                        };
                    });;
                    console.log("题目列表", this.questionList);
                })
                    .fail(err => {
                        this.loading = false;
                        console.log("错误信息", err.responseJSON.detail);
                        this.showMsg = err.responseJSON.detail;
                    });
            },
            //返回或退出
            exit() {
                if (window.jsBridge) {
                    window.jsBridge.navigateBack();
                } else {
                    console.log("navigateBack 未找到jsBridge");
                }

            },
            //答题结束批量回传答题结果
            submitResults() {
                //游戏名称（string）|题号（数字123）|是否正确（0：错误、1：正确）|错误信息（如果正确，写无。如果错误，写正确答案是什么。）

                //第一题正确
                //window.jsBridge.log(`${logTitle}|${1}|${1}|无`);
                //第二题错误
                //window.jsBridge.log(`${logTitle}|${2}|${0}|正确答案是${"环形交叉路口"}：但是玩家错误的选择了${"四车道及以上公路交叉路口预告"}`);
                this.questionList.map((item, index) => {
                    let log_data_arr = [];

                    log_data_arr.push(logTitle);

                    if (logMode == "index") {
                        log_data_arr.push(index + 1);
                    } else if (logMode == "id") {
                        log_data_arr.push(item.id);
                    }

                    const right = item.choices.find(i => i.isAnswer);
                    if (right.prefix === this.choicesList[index]) {
                        log_data_arr.push(1);
                        log_data_arr.push("无");
                    } else {
                        log_data_arr.push(0);
                        const wrong = item.choices.find(i => i.prefix === this.choicesList[index]);
                        log_data_arr.push(`正确答案是${right.content}：但是玩家错误的选择了${wrong.content}`);
                    }


                    if (window.jsBridge) {
                        window.jsBridge.log(log_data_arr.join("|"));
                    } else {
                        console.info(log_data_arr.join("|"));
                    }


                });
            }

        }

    })
</script>

</html>